import WxValidate from '../../utils/WxValidate'
var Mcaptcha = require('../../utils/mcaptcha.js');
const db = wx.cloud.database().collection('LinuxAppDash')
Page({
  data: {
    // 表单切换
    submitFormDenglu: true,
    submitFormZhuCe: false,
    submitFormFindpassWord: false,
    // input数据
    makecode: "",
    inputPhoneNumberValue: "",
    inputAuthPwdValue: "",
    code: '',
    randomCipher: '',
    mailPassWord: '',
    email: '',
    password: '',
    equalTo: '',
    mcaptcha: "",
  },
  sendEmail(type) {
    let that = this;
    wx.cloud.callFunction({
      name: "sendEmail",
      data: {
        userEmail: that.data.inputPhoneNumberValue,
        randomCipher: that.data.randomCipher,
        mailPassWord: that.data.mailPassWord,
        type: type
      },
      success(res) {
        wx.showToast({
          title: '密码发送成功，请留意邮箱信息',
          icon: 'none',
          duration: 2000,
        })
        that.setData({
          email: that.data.inputPhoneNumberValue,
          submitFormZhuCe: false,
          submitFormFindpassWord: false,
          submitFormDenglu: true,
        })
        that.createCode("canvas1");
      },
      fail(res) {}
    })
  },
  // 弹出框
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //登录表单信息验证
  submitFormDenglu(e) {
    const params = e.detail.value
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
    } else if (this.data.makecode != this.data.code) {
      wx.showToast({
        title: '验证码不正确',
        icon: 'none',
        duration: 2000,
      })
    } else {
      let that = this
      wx.cloud.database().collection('LinuxAppDash')
        .where({
          number: that.data.inputPhoneNumberValue,
          password: that.data.inputAuthPwdValue
        })
        .get({
          success: function (res) {
            if (res.data.length !== 0) {
              let data = res.data[0].number;
              wx.setStorageSync('userinfo', data)
              wx.navigateTo({
                url: '../index/index',
              })
            } else {
              wx.showToast({
                title: '登陆失败，账号或密码错误',
                icon: 'none',
                duration: 3000,
              })
              that.huanyizhang()
            }
          },
          fail: function (res) {}
        })
    }
  },
  submitFormZhuCe(e) {
    const params = e.detail.value
    // 传入表单数据，调用验证方法
    if (!this.WxValidate2.checkForm(params)) {
      const error = this.WxValidate2.errorList[0]
      this.showModal(error)
    } else if (this.data.makecode != this.data.code) {
      wx.showToast({
        title: '验证码不正确',
        icon: 'none',
        duration: 2000,
      })
    } else {
      wx.cloud.database().collection('LinuxAppDash')
        .where({
          number: this.data.inputPhoneNumberValue,
        })
        .get()
        .then(res => {
          if (res.data.length !== 0) {
            wx.showToast({
              title: '账号已被注册',
              icon: 'none',
              duration: 4000,
            })
          } else {
            this.createPassword(8);
            wx.cloud.database().collection('LinuxAppDash')
              .add({
                data: {
                  number: this.data.inputPhoneNumberValue,
                  password: this.data.randomCipher,
                }
              })
              .then(res => {
                wx.showToast({
                  title: '账号注册成功，请留意邮箱信息',
                  icon: 'none',
                  duration: 2000,
                })
                this.sendEmail()
              })
              .catch(res => {})
          }
        })
    }
  },
  submitFormFindpassWord(e) {
    const params = e.detail.value
    if (!this.WxValidate2.checkForm(params)) {
      const error = this.WxValidate2.errorList[0]
      this.showModal(error)
    } else if (this.data.makecode != this.data.code) {
      wx.showToast({
        title: '验证码不正确',
        icon: 'none',
        duration: 2000,
      })
    } else {
      wx.cloud.database().collection('LinuxAppDash')
        .where({
          number: this.data.inputPhoneNumberValue,
        })
        .get()
        .then(res => {
          if (res.data.length !== 0) {
            var mailPassWord = res.data[0].password;
            this.data.inputPhoneNumberValue = res.data[0].number
            this.data.mailPassWord = res.data[0].password;
            this.sendEmail(1)
          }
        })
    }
  },
  // 验证字段的规则
  initValidate() {
    const rules = {
      email: {
        required: true,
        email: true,
      },
      password: {
        required: true,
        minlength: 6,
        maxlength: 15,
      },
      equalTo: {
        required: true,
      }
    }
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      email: {
        required: '请输入QQ邮箱号',
        email: '请输入正确的QQ邮箱号',
      },
      password: {
        required: '请输入密码',
        minlength: '密码长度不少于6位',
        maxlength: '密码长度不多于15位',
      },
      equalTo: {
        required: '请输入验证码',
        equalTo: '请输入正确的验证码'
      },
    }
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  initValidate2() {
    const rules = {
      email: {
        required: true,
        email: true,
      },
      equalTo: {
        required: true,
      }
    }
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      email: {
        required: '请输入邮箱号',
        email: '请输入正确的QQ邮箱号',
      },
      equalTo: {
        required: '请输入验证码',
        equalTo: '请输入正确的验证码'
      },
    }
    // 创建实例对象
    this.WxValidate2 = new WxValidate(rules, messages)
  },
  // 点击忘记密码
  forgetPassWord() {
    this.setData({
      submitFormFindpassWord: !this.data.submitFormFindpassWord,
      submitFormDenglu: !this.data.submitFormDenglu,
      submitFormZhuCe: false
    })
    // this.huanyizhang()
    this.createCode("canvas3");

  },
  // 点击切换登录
  SwitchTheLogin() {
    this.setData({
      submitFormFindpassWord: !this.data.submitFormFindpassWord,
      submitFormDenglu: !this.data.submitFormDenglu,
      submitFormZhuCe: false
    })
    // this.huanyizhang()
    this.createCode("canvas1");
  },
  // 点击注册新账号
  registerNewProgress() {
    this.setData({
      submitFormFindpassWord: false,
      submitFormDenglu: !this.data.submitFormDenglu,
      submitFormZhuCe: !this.data.submitFormZhuCe,
    })
    // this.huanyizhang()
    this.createCode("canvas2");

  },
  // 点击注册页面的切换登录
  SwitchTheLoginTwo() {
    this.setData({
      submitFormFindpassWord: false,
      submitFormDenglu: !this.data.submitFormDenglu,
      submitFormZhuCe: !this.data.submitFormZhuCe,
    })
    // this.huanyizhang()
    this.createCode("canvas1");
  },
  // 点击换一张
  huanyizhang() {
    this.mcaptcha.refresh();
    this.setData({
      code: this.mcaptcha.options.createCodeImg,
    })
  },
  // 生成验证码
  createCode(el) {
    let width;
    let height;
    wx.getSystemInfo({
      success: function (res) {
        width = res.windowWidth * 0.2;
        height = res.windowHeight * 55 / 750;
      },
    })
    this.mcaptcha = new Mcaptcha({
      el: el,
      width: width,
      height: height,
      createCodeImg: "",
    });
    this.setData({
      code: this.mcaptcha.options.createCodeImg,
    })

  },
  // 随机生成密码
  createPassword(len) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < len; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    this.setData({
      randomCipher: text,
    })
  },
  //获取输入验证码
  makecodeInput: function (e) {
    this.setData({
      makecode: e.detail.value
    })
  },
  //input输入框输入的值
  bindPhoneNumberInput(e) {
    this.setData({
      inputPhoneNumberValue: e.detail.value
    })
  },
  bindAuthPwdInput(e) {
    this.setData({
      inputAuthPwdValue: e.detail.value
    })
  },
  //获取openid
  getOpenid() {
    let that = this;
    wx.login({
      success: function (res) { //请求自己后台获取用户openid
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session',
          data: {
            appid: 'wx4b01222c7d588672',
            secret: '3c70c3007b8fc34ba2cc71ef7a2da7ee',
            js_code: res.code,
            grant_type: "authorization_code"
          },
          success: function (response) {
            var openid = response.data.openid;

            //可以把openid存到本地，方便以后调用
            wx.setStorageSync('openid', openid);
            wx.cloud.database().collection('LinuxAppDash')
              .where({
                _openid: openid,
              })
              .get({
                success: function (res) {
                  if (res.data.length !== 0) {
                    let data = res.data[0].number;
                    wx.setStorageSync('userinfo', data)
                    wx.redirectTo({
                      url: '../index/index',
                    })
                  } else {
                    that.pagrInit()
                  }
                },
                fail: function (res) {
                  that.pagrInit()
                }
              })
          },
          fail: function (res) {
            that.pagrInit()
          }
        })
      },
      fail: function (res) {
        that.pagrInit()
      }
    })
  },
  pagrInit() {
    // 初始化验证码
    this.createCode("canvas1");

    //初始化表单
    this.initValidate();
    this.initValidate2();
  },
  onLoad: function (options) {
    //获取openid
     this.getOpenid();

    //页面初始化加载内容
    // this.pagrInit()
  },
})